<!-- 供应商管理-供应商认证列表（管理）  -->
<template>
  <div>
    <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    </pageHeader>
    <div class="search-box">
      <a-space>
        <div>
          <a-input-group>
            <a-select
              :style="{ width: '120px' }"
              placeholder="请选择"
              v-model="currSelectVal"
            >
              <a-option value="number">供应商编号</a-option>
              <a-option value="name">供应商名称</a-option>
            </a-select>
            <a-input-search
              :style="{ width: 'auto' }"
              placeholder="请输入"
              v-model="currSelectSearch"
              @search="search"
              search-button
            />
          </a-input-group>
        </div>
      </a-space>
      <div>
        <a-space>
          <a-button type="outline" @click="reset">
            <template #icon>
              <icon-refresh />
            </template>
            <template #default>重置</template>
          </a-button>
          <a-button status="success">
            <template #icon>
              <icon-download />
            </template>
            <template #default>导入</template>
          </a-button>
          <a-button status="warning">
            <template #icon>
              <icon-export rotate="-90" />
            </template>
            <template #default>导出</template>
          </a-button>
          <a-button type="primary" @click="showFormHeaderSetting"
            >表头设置</a-button
          >
        </a-space>
      </div>
    </div>
    <div style="padding: 10px">
      <tableTurn :tableData="getData" :args="args" ref="tableTurnRef">
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column
          v-for="(item, index) in selectedHeader"
          :title="item.name"
          :key="index"
          :data-index="item.code"
          align="center"
          :width="200"
        >
          <template v-if="item.code === 'createdAt'" #cell="{ record }">
            {{ dayjs(record.createdAt).format('YYYY-MM-DD') }}
          </template>
          <!-- 认证项目item -->
          <template v-else-if="item.code === 'authState'" #cell="{ record }">
            <span>{{
              record.authState === 1
                ? '待认证'
                : record.authState === 2
                ? '认证合格'
                : record.authState === 3
                ? '认证不合格'
                : '无需认证'
            }}</span>
          </template>
          <!-- 任务下单人item -->
          <template
            v-else-if="item.code === 'createUserName'"
            #cell="{ record }"
          >
            <a-space class="auntContent" direction="vertical" fill>
              <div
                class="item"
                v-for="element in record.supplierAuth"
                :key="element.id"
                >{{ element.headManName }}
              </div>
            </a-space>
          </template>

          <!-- 执行状态item -->
          <template
            v-else-if="item.code === 'ExecutionStatus'"
            #cell="{ record }"
          >
            <a-space class="auntContent" direction="vertical" fill>
              <div
                class="item"
                v-for="element in record.supplierAuth"
                :key="element.id"
              >
                <a-space>
                  <!-- <a-typography-text style="cursor: pointer" type="primary">
                    {{
                      element.state === 4
                        ? '通知整改'
                        : element.state === 5
                        ? '通知整改'
                        : ''
                    }}
                  </a-typography-text> -->

                  <a-typography-text
                    ref="authSetTypeText"
                    type="primary"
                    style="cursor: pointer"
                    @click="jump(record, element)"
                  >
                    {{
                      element.state === 1
                        ? '任务下达'
                        : element.state === 2
                        ? '认证详情'
                        : element.state === 3
                        ? '认证详情'
                        : element.state === 4
                        ? '认证详情'
                        : element.state === 5
                        ? '认证详情'
                        : '任务下达'
                    }}
                  </a-typography-text>
                </a-space>
              </div>
            </a-space>
          </template>
        </a-table-column>

        <!-- 操作item -->
        <!-- <a-table-column align="center" :width="300" fixed="right" title="操作">
          <template #cell>
            <a-button type="text">产品详情</a-button>
          </template>
        </a-table-column> -->
      </tableTurn>
    </div>
    <FormHeaderSetting
      v-model:visible="formHeaderSettingVisible"
      title="供应商产品总览表头设置"
      :resultList="headerSetting.list"
      @headerSave="headerSave"
      :forbidList="forbidList"
    ></FormHeaderSetting>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import { pageData as IpageData } from '@/types/global';
  import {
    GetSupplierLevelInfo,
    addSupplierauth,
  } from '@/api/buy-management/supplier-management/base-setting';
  import {
    GetSupplierPrimaryList,
    DelSupplierPrimaryList,
    GetSupplierPrimaryHeaderList,
    PutSupplierPrimaryHeaderList,
  } from '@/api/buy-management/supplier-management/supplier-primary-list';
  import { GetSupplierProductList } from '@/api/buy-management/supplier-management/supplier-product-overview/index';
  import cloneDeep from 'lodash.clonedeep';
  import dayjs from 'dayjs';
  import { formHeaderSetting } from '@/types/global';

  const router = useRouter();
  const authSetTypeText = ref();
  const title = '供应商产品总览';
  const breadCrumb = ['采购管理', '供应商管理', '供应商产品总览'];
  const UserInfo = JSON.parse(
    JSON.stringify(sessionStorage.getItem('loginInfo'))
  );

  const headerSetting = reactive<formHeaderSetting>({
    list: [],
  });

  const ModelVisible = ref(false);

  const forbidList = reactive(['salesName']); // 禁止移动的表头， (销售员)

  // 表格配置
  const args = reactive({
    stripe: true,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    },
    scroll: {
      y: 500,
    },
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });

  let tableTurnRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  let currNameSearch = ref(''); // 储存搜索供应商名称的值
  let isFirstSelect = ref(true);

  // 获取列表数据
  const getData = async (pageData?: any) => {
    try {
      let data = {};
      if (currSelectSearch.value !== '' && currSelectVal.value !== '')
        data[currSelectVal.value] = currSelectSearch.value;
      const res = await GetSupplierProductList({
        ...pageData,
        ...data,
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  let levelList = reactive<any>({
    list: [],
  });

  const getLevelData = async () => {
    try {
      const { data } = await GetSupplierLevelInfo();
      levelList.list = data;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  getLevelData();

  // 搜索按钮
  const search = () => {
    tableTurnRef.value.loadData();
  };
  // 重置按钮
  const reset = () => {
    currSelectSearch.value = '';
    currNameSearch.value = '';
    currSelectVal.value = '';
    tableTurnRef.value.loadData();
  };

  const addautn = () => {
    ModelVisible.value = true;
  };

  const addProject = async (formData, date, content, key) => {
    if (key === 1) {
      await addSupplierauth({
        id: formData.id,
        submitDemandTime: date,
        flowStr: content,
      });
    } else {
      await addSupplierauth({
        id: formData.id,
        submitDemandTime: date,
        flowStr: `${content}`,
      });
    }
  };

  // 监听键盘回车，按了回车也会查询
  const keyDown = (e: any) => {
    if (e.keyCode === 13) {
      tableTurnRef.value.loadData();
    }
  };

  onMounted(() => {
    // 监听键盘事件
    window.addEventListener('keydown', keyDown);
  });

  const jump = (e, val) => {
    if (val.authSetType === 1) {
      router.push({
        name: 'SupplierRegistrationSampletask',
        query: { gys: JSON.stringify(e), aunt: JSON.stringify(val) },
      });
    } else if (val.authSetType === 2) {
      router.push({
        name: 'FieldCertification',
        query: { gys: JSON.stringify(e), aunt: JSON.stringify(val) },
      });
    }
  };

  // 获取表头设置列表
  const getHeaders = async () => {
    try {
      const tableHead = await GetSupplierPrimaryHeaderList({
        supplierType: 6,
        userId: UserInfo.id,
      });
      headerSetting.list = tableHead.extends;
    } catch (error: unknown) {
      console.log(error);
    }
  };
  getHeaders();

  // 在表格上显示的表头;
  const selectedHeader = computed(() => {
    const arr: formHeaderSetting['list'] = [];
    headerSetting.list.forEach((item) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  let formHeaderSettingVisible = ref<boolean>(false); // 是否显示表头设置组件

  // 表头设置按钮
  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  // 表头设置保存后返回的自定义事件
  const headerSave = async (headerList: formHeaderSetting['list']) => {
    try {
      const data = {
        supplierType: 6,
        userId: UserInfo.id,
        extend: JSON.stringify(headerList),
      };
      await PutSupplierPrimaryHeaderList(data);
      headerSetting.list = [...headerList];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // let TypeColor

  let currId = ref(-1); // 储存当前选中的id

  // 去往对应的详情页面
  const goDetail = (id: number) => {
    router.push({
      name: 'ArchivalInformation',
      query: {
        id,
        type: 1,
      },
    });
  };

  // 删除一项
  const deleteItem = async (id: number) => {
    try {
      await DelSupplierPrimaryList({
        id,
      });
      tableTurnRef.value.loadData();
    } catch (err: unknown) {
      console.log(err);
    }
  };
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
    margin-top: -7px;
  }

  :deep(.arco-space-item) {
    margin-top: 10px;
  }
  .auntContent {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .aunt-item {
    width: 100px;
    height: 40px;
    line-height: 40px;
    border: 1px solid rgba(229, 230, 235);
    border-radius: 5px;
  }

  .item {
    width: 100px;
    height: 40px;
    line-height: 40px;
  }

  .WaitSubmitted {
    // 待下达
    background: #c9cdd4;
    color: rgb(255, 255, 255);
    border: none;
  }
  .Examining {
    // 执行中
    background: rgb(216, 229, 255);
    color: #165dff;
    border: none;
  }
  .Pass {
    // 已通过
    background-color: rgba(214, 243, 229);
    color: #31c27c;
    border: none;
  }
  .NoPass {
    //不通过
    background-color: rgb(255, 204, 204);
    border: none;
    color: #f53f3f;
  }
  .Qualified {
    // 待执行
    background: rgba(255, 247, 232);
    border: none;
    color: #ff9a2e;
  }
</style>
